import React from "react";
import type { FormProps } from "antd";
import { Button, Checkbox, Form, Input, Flex, message } from "antd";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { post } from "../../utils/request";
import { useNavigate } from "react-router-dom";

type FieldType = {
  username: string;
  password: string;
};

function Login() {
    const navigate = useNavigate();

  const loginFn = async (username: string, password: string) => {
    return await post("/user/login", {
      username,
      password,
    });
  };

  const onFinish: FormProps<FieldType>["onFinish"] =async (values) => {
    const res = await loginFn(values.username, values.password);
    if (res.status === 200 || res.status === 201) {
      message.success("登录成功");
      navigate("/");
    } 
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Flex
      justify="center"
      align="center"
      style={{ width: "100vw", height: "100vh", backgroundColor: "#f0f2f5" }}
    >
      <div>
        <h1 style={{ textAlign: "center", fontSize: 40 }}>图书管理系统</h1>
        <Form
          name="basic"
          style={{ width: 600 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            name="username"
            rules={[
              { required: true, message: "请输入用户名" },
              { min: 6, message: "用户名长度不能小于6位" },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item<FieldType>
            name="password"
            rules={[
              { required: true, message: "请输入密码" },
              { min: 6, message: "密码长度不能小于6位" },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
            />
          </Form.Item>


          <Form.Item style={{ width: "100%", textAlign: "right" }}>
            <div className="links">
              <a href="/register" style={{ color: "#1677ff" }}>
                没有账号？去注册
              </a>
            </div>
          </Form.Item>
          <Form.Item label={null}>
            <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </Flex>
  );
}
export default Login;
